//package com.eatme.web.sys.workflow.camunda.controller;
//
//import com.eatme.web.common.QueryCondition;
//import com.eatme.web.common.vo.AppResponse;
//import com.eatme.web.sys.workflow.camunda.CamundaServiceImpl;
//import org.apache.commons.io.FilenameUtils;
//import org.camunda.bpm.engine.HistoryService;
//import org.camunda.bpm.engine.RepositoryService;
//import org.camunda.bpm.engine.RuntimeService;
//import org.camunda.bpm.engine.TaskService;
//import org.camunda.bpm.engine.history.HistoricActivityInstance;
//import org.camunda.bpm.engine.history.HistoricProcessInstance;
//import org.camunda.bpm.engine.history.HistoricTaskInstance;
//import org.camunda.bpm.engine.repository.Deployment;
//import org.camunda.bpm.engine.repository.ProcessDefinition;
//import org.camunda.bpm.engine.task.Task;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.security.Principal;
//import java.util.*;
//
//// @RestController
//@RequestMapping("/process/instance/task/")
//public class CamundaController {
//
//    private static final Logger LOG = LoggerFactory.getLogger(CamundaController.class);
//
//    final
//    TaskService taskService;
//
//    final
//    RuntimeService runtimeService;
//
//    final
//    RepositoryService repositoryService;
//
//    final
//    CamundaServiceImpl camundaServiceImpl;
//
//    final
//    HistoryService historyService;
//
//    public CamundaController(TaskService taskService, RuntimeService runtimeService, RepositoryService repositoryService, CamundaServiceImpl camundaServiceImpl, HistoryService historyService) {
//        this.taskService = taskService;
//        this.runtimeService = runtimeService;
//        this.repositoryService = repositoryService;
//        this.camundaServiceImpl = camundaServiceImpl;
//        this.historyService = historyService;
//    }
//
//
//    //用户历史任务
//    @PostMapping(value = "/process/instance/history/userList")
//    public AppResponse InstancesByUser(@RequestBody QueryCondition<Map<String,Object>> queryCondition, Principal principal) {
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getPageIndex();
//        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
//                .orderByHistoricTaskInstanceEndTime().asc().taskAssignee(principal.getName()).listPage(pageIndex,pageSize);
//        List<Map<String, Object>> arrayList = new ArrayList<>();
//        for (HistoricTaskInstance hti : historicTaskInstances) {
//            HashMap<String, Object> hashMap = new HashMap<>();
//            hashMap.put("id", hti.getId());
//            hashMap.put("startTime", hti.getStartTime());
//            hashMap.put("endTime", hti.getEndTime());
//            hashMap.put("description", hti.getDescription());
//            hashMap.put("deleteReason", hti.getDeleteReason());
//            arrayList.add(hashMap);
//        }
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("total",historyService.createHistoricTaskInstanceQuery()
//                .orderByHistoricTaskInstanceEndTime().asc().taskAssignee(principal.getName()).count());
//        if (!historicTaskInstances.isEmpty()){
//            resultMap.put("list",arrayList);
//        }
//        return AppResponse.ok().data(resultMap);
//    }
//
//    //任务实例历史
//    @PostMapping(value = "/process/instance/history/list")
//    public AppResponse listByProcessInstanceId(@RequestBody QueryCondition<Map<String,Object>> queryCondition) {
//        String processInstanceId = (String) queryCondition.getCondition().get("processInstanceId");
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getPageIndex();
//        //--------------------------------------------另一种写法-------------------------
//        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().
//                orderByHistoricTaskInstanceEndTime().asc().processInstanceId(processInstanceId).listPage(pageIndex,pageSize);
//        List<Map<String, Object>> arrayList = new ArrayList<>();
//        for (HistoricTaskInstance hti : historicTaskInstances) {
//            HashMap<String, Object> hashMap = new HashMap<>();
//            hashMap.put("id", hti.getId());
//            hashMap.put("startTime", hti.getStartTime());
//            hashMap.put("endTime", hti.getEndTime());
//            hashMap.put("description", hti.getDescription());
//            hashMap.put("deleteReason", hti.getDeleteReason());
//            arrayList.add(hashMap);
//        }
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("total",historyService.createHistoricTaskInstanceQuery()
//                .orderByHistoricTaskInstanceEndTime().asc().count());
//        if (!historicTaskInstances.isEmpty()){
//            resultMap.put("list",arrayList);
//        }
//        return AppResponse.ok().data(resultMap);
//    }
//
//    //流程图高亮
//    @GetMapping("/process/instance/history/highlight/{id}")
//    public AppResponse gethighLine(@PathVariable(value = "id") String processInstanceId, Principal principal) {
//        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
//        //获取bpmnModel对象
//        // TODO
////        BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
////        //因为我们这里只定义了一个Process 所以获取集合中的第一个即可
////        Process process = bpmnModel.getProcesses().get(0);
////        //获取所有的FlowElement信息
////        Collection<FlowElement> flowElements = process.getFlowElements();
////        Map<String, String> map = new HashMap<>();
////        for (FlowElement flowElement : flowElements) {
////            //判断是否是连线
////            if (flowElement instanceof SequenceFlow) {
////                SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
////                String ref = sequenceFlow.getSourceRef();
////                String targetRef = sequenceFlow.getTargetRef();
////                map.put(ref + targetRef, sequenceFlow.getId());
////            }
////        }
//        //获取流程实例 历史节点(全部)
//        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
//        //各个历史节点   两两组合 key
//        Set<String> keyList = new HashSet<>();
//        for (HistoricActivityInstance i : list) {
//            for (HistoricActivityInstance j : list) {
//                if (i != j) {
//                    keyList.add(i.getActivityId() + j.getActivityId());
//                }
//            }
//        }
//        //高亮连线ID
//        Set<String> highLine = new HashSet<>();
//        // TODO
//        // keyList.forEach(s -> highLine.add(map.get(s)));
//        //获取流程实例 历史节点（已完成）
//        List<HistoricActivityInstance> listFinished = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).finished().list();
//        //高亮节点ID
//        Set<String> highPoint = new HashSet<>();
//        listFinished.forEach(s -> highPoint.add(s.getActivityId()));
//
//        //获取流程实例 历史节点（待办节点）
//        List<HistoricActivityInstance> listUnFinished = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).unfinished().list();
//        //需要移除的高亮连线
//        Set<String> set = new HashSet<>();
//        //待办高亮节点
//        Set<String> waitingToDo = new HashSet<>();
//        listUnFinished.forEach(s -> {
//            waitingToDo.add(s.getActivityId());
//            // TODO
////            for (FlowElement flowElement : flowElements) {
////                //判断是否是 用户节点
////                if (flowElement instanceof UserTask) {
////                    UserTask userTask = (UserTask) flowElement;
////
////                    if (userTask.getId().equals(s.getActivityId())) {
////                        // List<SequenceFlow> outgoingFlows = userTask.getOutgoingFlows();
////                        Collection<SequenceFlow> outgoingFlows = userTask.getOutgoing();
////                        //因为 高亮连线查询的是所有节点  两两组合 把待办 之后  往外发出的连线 也包含进去了  所以要把高亮待办节点 之后 即出的连线去掉
////                        if (outgoingFlows != null && outgoingFlows.size() > 0) {
////                            outgoingFlows.forEach(a -> {
////                                // TODO
//////                                if (a.getSourceRef().equals(s.getActivityId())) {
//////                                    set.add(a.getId());
//////                                }
////                            });
////                        }
////                    }
////                }
////            }
//        });
//        highLine.removeAll(set);
//        //获取当前用户
//        //User sysUser = getSysUser();
//        Set<String> iDo = new HashSet<>(); //存放 高亮 我的办理节点
//        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery().taskAssignee(principal.getName()).finished().processInstanceId(processInstanceId).list();
//        taskInstanceList.forEach(a -> iDo.add(a.getTaskDefinitionKey()));
//        Map<String, Object> resultMap = new HashMap<>();
//        resultMap.put("highlightElement", highPoint);
//        resultMap.put("highlightConnection", highLine);
//        resultMap.put("waitingToDoElement", waitingToDo);
//        resultMap.put("iDoElement", iDo);
//        // TODO
//        // resultMap.put("id",historicProcessInstance.getDeploymentId());
//        return AppResponse.ok().data(resultMap);
//    }
//
//
//
//    @PostMapping("/process/definition/uploadStreamAndDeploy")
//    @ResponseBody
//    public AppResponse uploadStreamAndDeployment(@RequestParam("file") MultipartFile file, @RequestParam("deploymentName") String deploymentName) throws IOException {
//        AppResponse<Deployment> appResponse = camundaServiceImpl.deploy(file,deploymentName);
//        LOG.debug("{}",appResponse.getData().toString());
//        Map<String, Object> map = new HashMap<>();
//        map.put("deploymentId", appResponse.getData().getId());
//        return AppResponse.ok().data(map);
//    }
//
//    //添加流程定义通过在线提交bpmn的xml
//    @PostMapping("/process/definition/uploadStringAndDeployment")
//    @ResponseBody
//    public AppResponse uploadStringAndDeployment(@RequestBody  Map<String,Object> map) {
//        String text = (String) map.get("text");
//        Deployment deployment = null;
//        deployment = repositoryService.createDeployment()// 初始化部署
//                .addString("createWithBPMNJS.bpmn", text)
//                //.name(deploymentName)
//                .deploy();
//        return AppResponse.ok();
//    }
//
//    //获取流程定义列表
//    @PostMapping("/process/definition/list")
//    @ResponseBody
//    public AppResponse definitionList(@RequestBody QueryCondition<Map<String,Object>> queryCondition) {
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getPageIndex();
//        List<Map<String,Object>> listMap = new ArrayList<>();
//        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage(pageIndex,pageSize);
//        for(ProcessDefinition processDefinition: list) {
//            HashMap<String,Object> hashMap = new HashMap<>();
//            hashMap.put("name",processDefinition.getName());
//            hashMap.put("key",processDefinition.getKey());
//            hashMap.put("resourceName",processDefinition.getResourceName());
//            hashMap.put("deploymentId",processDefinition.getDeploymentId());
//            hashMap.put("version",processDefinition.getVersion());
//            listMap.add(hashMap);
//        }
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("total",repositoryService.createDeploymentQuery().count());
//        if (!list.isEmpty()){
//            resultMap.put("list",listMap);
//        }
//        return AppResponse.ok().data(resultMap);
//    }
//
//    //获取流程定义xml
//    @RequestMapping(value = "/process/definition/detail/{id}", produces = {"text/xml"}, method = RequestMethod.GET)
//    public void getDefinitionXML(HttpServletResponse response, @PathVariable(value = "id") String deploymentId) throws IOException {
////        String deploymentId = (String) map.get("deploymentId");
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
//        InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
//        int count = inputStream.available();
//        byte[] bytes = new byte[count];
//        response.setContentType(MediaType.TEXT_XML_VALUE);
//        response.setCharacterEncoding("utf-8");
//        OutputStream outputStream = response.getOutputStream();
//        while (inputStream.read(bytes) != -1) {
//            outputStream.write(bytes);
//        }
//        inputStream.close();
//    }
//
//    //获取流程部署列表
//    @PostMapping("/process/deployment/list")
//    @ResponseBody
//    public AppResponse deploymentList(@RequestBody QueryCondition<Map<String,Object>> queryCondition) {
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getCurrentPage();
//        List<Map<String,Object>> listMap = new ArrayList<>();
//        List<Deployment> list = repositoryService.createDeploymentQuery().listPage((pageIndex-1)*pageSize,pageSize);
//        for(Deployment deployment: list) {
//            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
//            HashMap<String,Object> hashMap = new HashMap<>();
//            hashMap.put("id",deployment.getId());
//            hashMap.put("name",deployment.getName());
//            hashMap.put("deploymentTime",deployment.getDeploymentTime());
//            //hashMap.put("version",deployment.getVersion());
//            //hashMap.put("key",deployment.getKey());
//            hashMap.put("processDefinitionName",processDefinition.getName());
//            hashMap.put("processDefinitionKey",processDefinition.getKey());
//            hashMap.put("resourceName",processDefinition.getResourceName());
//            hashMap.put("processDefinitionVersion",processDefinition.getVersion());
//            listMap.add(hashMap);
//        }
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("total",repositoryService.createDeploymentQuery().count());
//        if (!list.isEmpty()){
//            resultMap.put("list",listMap);
//        }
//        return AppResponse.ok().data(resultMap);
//    }
//
//    //删除流程定义
//    @PostMapping("/process/definition/delete")
//    @ResponseBody
//    public AppResponse deleteDefinition(@RequestBody Map<String,Object> map) {
//        String deploymentId = (String) map.get("deploymentId");
//        String definitionId = (String) map.get("definitionId");
//        //删除数据
////        int result = activitiServiceImpl.delete(definitionId);
//        repositoryService.deleteDeployment(deploymentId,true);
//        return AppResponse.ok();
//    }
//
//    @PostMapping("process/instance/list")
//    @ResponseBody
//    public AppResponse uploadStreamAndDeployment(@RequestBody QueryCondition<Map<String,Object>> queryCondition)  {
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getPageIndex();
//        // TODO 获取所有流程实例
////        RuntimeService runtimeService = processEngine.getRuntimeService();
////        runtimeService.process
//        // 需要登陆
//        return AppResponse.ok();
//    }
//
//
//
//
//
//    @PostMapping(value = "list")
//    public AppResponse getTasks(@RequestBody QueryCondition<Map<String,Object>> queryCondition) {
//        Integer pageSize = queryCondition.getPage().getPageSize();
//        Integer pageIndex = queryCondition.getPage().getPageIndex();
//        List<org.camunda.bpm.engine.task.Task>  tasks = taskService.createTaskQuery().listPage(pageIndex,pageSize);
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("total", taskService.createTaskQuery().count());
//        if (!tasks.isEmpty()){
//            resultMap.put("list",tasks);
//        }
//        return AppResponse.ok().data(resultMap);
//    }
//
//    //完成待办任务
//    @PostMapping(value = "/complete/{id}")
//    public AppResponse complete(@PathVariable(value = "id") String  taskId) {
//        Task task = (Task) taskService.createTaskQuery().taskId(taskId);
////        if (task.getAssignee() == null) {
////            // 拾取任务
////            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
////        }
//        Map<String,Object> map = new HashMap<>();
//        taskService.complete(taskId,map);
//        return AppResponse.ok();
//    }
//
//}
